package com.kasax.skin.support.corel;

import android.app.Application;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.res.AssetManager;
import android.content.res.Resources;
import android.text.TextUtils;

import com.kasax.skin.support.utils.LogUtils;

import java.lang.reflect.Method;
import java.util.Observable;

public class SkinManager extends Observable {
    private static SkinManager instance;
    private Application mApp;

    private SkinManager() {

    }

    public SkinManager(Application application) {
        this.mApp = application;
        // 用于记录当前使用的皮肤
        SkinReference.init(application);
        // 资源管理类，用于从app/皮肤包中加载资源
        SkinResources.init(application);
        mApp.registerActivityLifecycleCallbacks(new SkinActivityLifecycle());

        // 加载皮肤
        loadSkin(SkinReference.getInstance().getSkin());
    }

    public static void init(Application application) {
        if (instance == null) {
            synchronized (SkinManager.class) {
                if (instance == null) {
                    instance = new SkinManager(application);
                }
            }
        }
    }

    public static SkinManager getInstance() {
        return instance;
    }

    public void loadSkin(String path) {
        if (!TextUtils.isEmpty(path)) {
            try {
                // 加载指定的皮肤包
                // 反射创建AssetManager对象
                AssetManager assetManager = AssetManager.class.newInstance();
                // 添加资源的路径
                Method addAssetPath = AssetManager.class.getDeclaredMethod("addAssetPath", String.class);
                // 加载指定路径的皮肤包
                addAssetPath.invoke(assetManager, path);

                // 当前App的Resource对象
                Resources appResources = this.mApp.getResources();
                // 皮肤包的Resource对象
                Resources skinResources = new Resources(assetManager, appResources.getDisplayMetrics(), appResources.getConfiguration());
                // 缓存当前使用的皮肤
                SkinReference.getInstance().setSkin(path);

                // 获取皮肤包的包名
                PackageManager packageManager = this.mApp.getPackageManager();
                PackageInfo packageArchiveInfo = packageManager.getPackageArchiveInfo(path, PackageManager.GET_ACTIVITIES);
                String packageName = packageArchiveInfo.packageName;
                SkinResources.getInstance().applySkin(skinResources, packageName);
            } catch (Exception e) {
                LogUtils.e(getClass(), e);
            }

        } else {
            // 记录使用默认皮肤
            SkinReference.getInstance().setSkin("");
            // 清空资源 管理器，皮肤资源 属性等
            SkinResources.getInstance().reset();
        }
        // 通知观察者
        setChanged();
        notifyObservers();
    }
}
